from __future__ import division
import pandas as pd
import numpy as np

from tqdm import tqdm


def cal_score_tianchi(result_with_score):
    MAP_FINAL = 0
    MAP_SCORE = {'satisfied': 0.7, 'delivered': 0.3}
    for cc in ['satisfied', 'delivered']:
        tmp = result_with_score.copy()
        tmp['rank'] = tmp.groupby(['user_id'])['score'].rank(ascending=False, method='first')
        tmp_score = tmp[tmp[cc] == 1]
        tmp_score['rank_1'] = tmp_score.groupby(['user_id'])['rank'].rank(ascending=True, method='first')
        tmp_score['AP'] = tmp_score['rank_1'] / tmp_score['rank']
        MAP = tmp_score.groupby(['user_id'])['AP'].mean().reset_index()['AP'].mean()
        MAP_FINAL = MAP_FINAL + MAP * MAP_SCORE[cc]
        print cc + 'MAP' + str(MAP)
    print(MAP_FINAL)